package org.cupk2.main.cecurity.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.cupk2.base.domain.CupkUserContextLoader;
import org.cupk2.base.domain.CupkUserContext;
import org.cupk2.base.jwt.CupkJwtClaims;
import org.cupk2.base.jwt.CupkJwtConfig;
import org.cupk2.base.jwt.CupkJwtUtils;
import org.cupk2.base.web.IpUtils;
import org.cupk2.main.cecurity.service.CupkUserOnlines;
import org.cupk2.service.inter.CupkUserServiceInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**在security检查用户权限前，验证JWT并进行用户授权
 * OncePerRequestFilter保证过滤器只执行一次
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private CupkUserServiceInter cupkUserService;
    /**
     * 是否在无授权时自动添加sysadmin为当前用户
     */
    @Value("${cupk2.test.auto.auth.able}")
    private boolean autoAuth;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (autoAuth) {

            if (StringUtils.isBlank(token)) {
                token = "sysadmin";
            }
            setSuccessUser(request, response, filterChain, cupkUserService.getUserByLoginName(token));
            return;
        }
        if (StringUtils.isBlank(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        CupkJwtClaims claims = CupkJwtUtils.parseJWT(token);
        if (claims == null) {
            filterChain.doFilter(request, response);
            return;
        }
        String loginId = (String) claims.get(CupkJwtConfig.ClaimsKey.LoginId);
        String loginname = (String) claims.get(CupkJwtConfig.ClaimsKey.LoginName);
        if (StringUtils.isBlank(loginname)) {
            filterChain.doFilter(request, response);
            return;
        }

        CupkUserContext userDetail = CupkUserOnlines.getUser(loginname, loginId, IpUtils.getClientIp(request), cupkUserService);
        {

            setSuccessUser(request, response, filterChain, userDetail);
        }
    }

    private void setSuccessUser(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, CupkUserContext userDetail) throws ServletException, IOException {
        userDetail.setIp(IpUtils.getClientIp(request));
        CupkUserContextLoader.put(userDetail);
        filterChain.doFilter(request, response);
    }
}
